defmodule AppConfigure do

    use ExActor.GenServer, export: :configure
    require Logger
    @table_name :env_configure
    @default_path "./configure.exs"
    @run_mode_key "RUN_MODE"

    def root_path do
        fetch(:project_path)
    end

    defstart start_link(env_var) do
        :ets.new(@table_name, [:protected, :named_table])
        config_path = System.get_env(env_var, @default_path)
        IO.inspect {"module...:", __MODULE__, ", line...", __ENV__.line, ", 配置文件路径...", config_path}
        merge_exs(config_path)
        initial_state(%{:config_path => config_path})
    end

    defcall refresh(), state: %{:config_path => config_path} = _s do
        merge_exs(config_path)
        reply(list())
    end

    defp merge_exs(config_path) do
        try do
            Code.eval_file(config_path)
            conf = ResourceConfigure.configure
            Enum.each(
                conf,
                fn {k, v} ->
                    :ets.insert(@table_name, {k, v})
                end
            )
        rescue
            err ->
                Logger.error("MergeExsError, reason:#{inspect(err)}, stacktrace:#{__STACKTRACE__}")
        end

    end

    def fetch(key) do
        case :ets.lookup(@table_name, key) do
            [{_, value} | _] -> value
            _ -> nil
        end
    end

    def list do
        :ets.tab2list(@table_name)
    end

    def run_mode() do
        fetch(@run_mode_key)
    end

    def is_prod() do
        run_mode = run_mode()
        if run_mode == "prod", do: true, else: false
    end

    def is_dev() do
        run_mode = run_mode()
        if run_mode == "dev", do: true, else: false
    end

end
